<?php
/**
 * Created by PhpStorm.
 * User: YAN
 * Date: 2017/7/24
 * Time: 13:07
 */

namespace App\Http\Controllers\API\English;

use App\Http\Controllers\Controller;
use App\Models\AdminLog;
use App\Models\Classes;
use App\Models\ClassStudent;
use App\Models\EnglishResults;
use App\Models\Student;
use App\Models\StudentEp;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class EnglishController extends Controller
{
    private $successNum = 0;
    private $errorNum = 0;
    private $user = 0;

    /**
     * 导入考试
     * @param Request $request
     */

    public function import(Request $request)
    {
//        return response($this->errorArr, 406);
        ini_set('max_execution_time', '0');
        $this->errorArr = [];
        if ($request->ajax()) {
            $this->user = $request->get('user');
            $semester_id = $request->get('opening');
            $file = $request->file('file');
            // 第一个参数代表目录, 第二个参数代表我上方自己定义的一个存储媒介
            $extension = $file->getClientOriginalExtension();
            $savePath = public_path('') . '/files_store';
            $filename = 'EnglishProficiencydaoru.' . $extension;

            $file->move($savePath, $filename);
//            $path = $file->store('avatars', 'uploads');
            Excel::load($savePath . '/' . $filename, function ($reader) use ($semester_id) {
                $reader1 = $reader->getSheet(0);
                $results = $reader1->toArray();
                foreach ($results as $key => $items) {
                    $kch = $items[0];
                    $xh = $items[1];
                    $kssj = $items[2];
                    $kxh = $items[3];
                    $kccj = $items[5];
                    $jdcj = $items[11];
                    $xm = $items[12];
                    $kcm = $items[29];
                    $ticket = $items[31];
                    $xf = $items[36];
                    if ($key == 0) {
                        continue;
                    }
                    \DB::beginTransaction();
                    try {
                        $student = Student::query()->where('u_code', $xh)
                            ->first();
                        if (!$student) {
                            $student = new Student();
                            $student->u_name = $xm;
                            $student->u_code = $xh;
                            $student->school = '暂无';
                            $student->access_token = str_random(60);
                            if (!$student->save()) {
                                throw new \Exception(var_dump($student->getErrors()));
                            }
                        }
                        $english = DB::table('english_results')
                            ->where(['s_id' => $student->id, 'semester_id' => $semester_id, 'e_number' => trim($kch), 'serial_number' => trim($kxh)])->first();
                        if (!$english) {
                            $english = new EnglishResults();
                            $english->e_number = $kch;
                            $english->semester_id = $semester_id;
                            $english->serial_number = $kxh;
                            $english->e_name = $kcm;
                            $english->e_jd_codes = $jdcj;
                            $english->e_codes = $kccj;
                            $english->s_id = $student->id;
                            $english->credit = $xf;
                            $english->time = strtotime($kssj);
                            $english->is_required = 1;
                            $english->ticket =$ticket;
                            if ($kxh >= 97) {
                                $english->is_make_up = 1;
                            }
                            if (!$english->save()) {
                                throw new \Exception(var_dump($english->getErrors()));
                            }
                        }
                        \DB::commit();
                        $this->successNum += 1;
                    } catch (\Exception $e) {
                        \DB::rollBack();
                       // dd($e->getMessage());
                        $this->errorNum += 1;
                    }
                }
                $logs = new AdminLog();
                $logs->admin = $this->user;
                $logs->logs = '导入英语等级考试信息，成功' . $this->successNum . '条，失败' . $this->errorNum . '条';
                $logs->save();
                if ($this->errorNum) {
                    return response($this->errorNum, 406);
                } else {
                    return response('导入失败', 200);
                }

            });
//            return ;
        }
    }

    public function index(Request $request)
    {
        $queryString = $request->get('query', '');
        $select = $request->get('select', '');
        $query = EnglishResults::with('Students')
            ->where('e_name', 'like', '%' . $queryString . '%');
        if (!empty($select)) {
            $query->where(['semester_id' => $select]);
        }
        $models = $query->paginate();
        return $models;
    }


    /**
     * 添加科室
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request)
    {
        $model = new EnglishResults();
        $model->fill($request->all());
        if ($model->save()) {
            return $model;
        } else {
            return response($model->getErrors()->toArray(), 406);
        }
    }


    /**
     * 修改员工
     * @param User $User
     * @param Request $request
     * @return mixed
     */
    public function update(EnglishResults $EnglishProficiency, Request $request)
    {
        $EnglishProficiency->fill($request->all());
        if ($EnglishProficiency->save()) {
            return $EnglishProficiency;
        } else {
            return response($EnglishProficiency->getErrors()->toArray(), 406);
        }
    }


    /**
     * 删除
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        $model = $this->findModel($id);
        try {
            $student = Student::query()->where(['id'=>$model->s_id])->first();
            $logs = new AdminLog();
            $logs->admin = Auth::user()->id;
            $logs->logs = '删除'.$student->u_name.'的四六级考试成绩信息。';
            if (!$logs->save()) {
                throw new \Exception('记录保存失败');
            }
            $model->delete();
            return ['state' => 'success'];
        } catch (\Exception $e) {
            return ['state' => 'failed', 'message' => $e->getMessage()];
        }
    }


    /**
     * 返回单个实例
     * @param User $user
     * @return mixed
     */
    public function show($id)
    {
        return $this->findModel($id);
    }


    /**
     * @param $id
     * @return Staff
     */
    public function findModel($id)
    {
        $model = EnglishResults::with('Students')->findOrFail($id);
        return $model;
    }
}